#packages
need = c(
  "dplyr",       #data structuring
  "scales",      #rescale
  "tidyr"        #drop_na
)
#load & install packages if necessary
have = need %in% rownames(installed.packages())
if ( any(!have) ) { install.packages( need[!have] ) }
pack <- lapply(need, library, character.only = TRUE)
rm(have,need,pack)

#load data
load("D:/POBE/datasets/anes_Dat.Rdata")

# Make separate data frames
# Ideological self-ID
anes_Polviews <- anes_Dat %>%
  select(year, genPew, genDec, ageGroup, polviews, partyid, white, college, protcattend) %>%
  drop_na() %>%
  droplevels() %>%
  mutate(across(c(polviews, partyid), ~rescale(., to = c(0, 1))))

anes_Polviews$att <- anes_Polviews$polviews

anes_Swelfare <- anes_Dat %>%
  select(year, genPew, genDec, ageGroup, starts_with('gov'), spendwp, partyid, white, college, protcattend) %>%
  drop_na() %>%
  droplevels() %>%
  mutate(across(c(starts_with('gov'), spendwp, partyid), ~rescale(., to = c(0, 1))))

anes_Swelfare$att <- rowMeans(select(anes_Swelfare, starts_with('gov'), spendwp))

anes_Racgender <- anes_Dat %>%
  select(year, genPew, genDec, ageGroup, blkaid, womnequal, partyid, white, college, protcattend) %>%
  drop_na() %>%
  droplevels() %>%
  mutate(across(c(blkaid, womnequal, partyid), ~rescale(., to = c(0, 1))))

anes_Racgender$att <- rowMeans(select(anes_Racgender, blkaid, womnequal))

anes_Cultmoral <- anes_Dat %>%
  select(year, genPew, genDec, ageGroup, abortlaw2, thermgays, starts_with('val'), partyid, white, college, protcattend) %>%
  drop_na() %>%
  filter(!genPew == "Greatest") %>%
  droplevels() %>%
  mutate(across(c(starts_with('val'), thermgays, abortlaw2, partyid), ~rescale(., to = c(0, 1))))

anes_Cultmoral$convalue  <- rowMeans(select(anes_Cultmoral, starts_with('val')))
anes_Cultmoral$att       <- rowMeans(select(anes_Cultmoral, thermgays, abortlaw2, convalue))

anes_Blkaid <- anes_Dat %>%
  select(year, genPew, genDec, ageGroup, blkaid, partyid, white, college, protcattend) %>%
  drop_na() %>%
  droplevels() %>%
  mutate(across(c(blkaid, partyid), ~rescale(., to = c(0, 1))))

anes_Blkaid$att <- anes_Blkaid$blkaid

# Convert from tibble to data frame
anes_Polviews  <- as.data.frame(anes_Polviews)
anes_Swelfare  <- as.data.frame(anes_Swelfare)
anes_Racgender <- as.data.frame(anes_Racgender)
anes_Cultmoral <- as.data.frame(anes_Cultmoral)
anes_Blkaid    <- as.data.frame(anes_Blkaid)